package com.hubu.client;
import com.alibaba.fastjson.JSON;
import com.hubu.core.Result;
import com.hubu.json.Command;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Client {
    private byte[] buffer=new byte[1024];
    private int port;
    private Socket socket;
    public Client(int port){
        this.port=port;
    }
    public void connect(){
        try {
            socket=new Socket();
            socket.connect(new InetSocketAddress(port));
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream();
            Command command=new Command();
            command.setCommandType("put");
            command.setKey("name");
            command.setValue("lugang");
            String s = JSON.toJSONString(command);
            byte[] buffer= s.getBytes(StandardCharsets.UTF_8);
            outputStream.write(buffer);
            //处理读事件
            Result result = processRead(socket.getInputStream());
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public Result processRead(InputStream inputStream)  {
        int read=0;
        Result result=null;
        StringBuilder stringBuilder=new StringBuilder();
        try{
            while((read=inputStream.read(buffer))!=-1){
                String item=new String(buffer,0,read);
                stringBuilder.append(item);
            }
            result = JSON.parseObject(stringBuilder.toString(), Result.class);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }
    public static void main(String[] args) {
        Client client=new Client(9090);
        client.connect();
    }
}
